package Network

import (
	"SQL/myDB"
	"fmt"
	"io"
	"logs"
	"mime/multipart"
	"net/http"
	"os"
)

var (
	publicFileDir        = "./public"
	privateFileDir       = "./private"
	maxIconSize    int64 = 20 << 20
)

func alterIcon(w http.ResponseWriter, req *http.Request) (code int, msg string, result interface{}) {
	code = Success
	err := req.ParseMultipartForm(32 << 20)
	if err != nil {
		code = errParseForm
		msg = err.Error()
		return
	}
	//logs.Print(req.Form)
	//logs.Print(req.MultipartForm)
	token := req.FormValue("token")
	code, msg, userID := judgeToken(token)
	if code != Success {
		return
	}
	objectID := req.FormValue("objectID")
	if objectID == "" {
		objectID = userID
	}
	if code, msg = IsGroupID(objectID); code == Success {
		code, msg = IsGroupManager(userID, objectID)
		if code != Success {
			return
		}
	} else {
		if objectID != userID {
			code = errNoPermission
			msg = "不允许改他人头像！"
			return
		}
	}

	icon, _, err := req.FormFile("icon")
	if statInterface, ok := icon.(Stat); ok {
		fileInfo, err := statInterface.Stat()
		if err == nil {
			if fileInfo.Size() > (maxIconSize) {
				code = errParseFileFailed
				msg = fmt.Sprint("上传文件不要超过", maxIconSize>>20, "M")
				return
			}
		} else if sizeInterface, ok := icon.(Size); ok {
			if sizeInterface.Size() > (maxIconSize) {
				code = errParseFileFailed
				msg = fmt.Sprint("上传文件不要超过", maxIconSize>>20, "M")
				return
			}
		}
	}
	if err != nil {
		code = errParseFileFailed
		msg = err.Error()
		return
	}
	defer icon.Close()
	return dealAlterIcon(objectID, icon)
}
func dealAlterIcon(userID string, icon multipart.File) (code int, msg string, result interface{}) {
	fileName := "/icon/" + userID + ".ico"
	code, msg = saveFile(fileName, icon, publicFileDir, maxIconSize)
	if code != Success {
		return code, msg, nil
	}
	err := myDB.ExecSql("update objects set iconURL = $1 where id = $2", fileName, userID)
	if err != nil {
		return errDBExecFailed, err.Error(), nil
	}
	return Success, "", map[string]string{"IconURL": fileName}
}

func saveFile(fileName string, file multipart.File, fileDir string, maxSize int64) (code int, msg string) {
	err := os.Remove(publicFileDir + fileName)
	if err != nil {
		logs.Print(err.Error())
	}
	File, err := os.OpenFile(publicFileDir+fileName, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		code = errWriteFileFailed
		msg = err.Error()
		return
	}
	defer File.Close()
	n, err := io.Copy(File, file)
	if err != nil {
		code = errWriteFileFailed
		msg = err.Error()
		return
	}
	if n > (maxSize) {
		os.Remove(fileDir + fileName)
		code = errRequestEntityTooLarge
		msg = fmt.Sprint("上传文件不要超过", maxSize>>20, "M")
		return
	}
	return Success, ""
}
